<?php
/**
 * 报价单详情控制器
 */

namespace app\admin\controller;

use app\admin\traits\AdminSettingForm;
use app\admin\traits\SettingContent;
use app\common\model\Brand;
use app\common\model\Offer;
use app\common\model\OfferDetail;
use app\common\model\School;
use app\common\model\Send;
use app\common\model\Spec;
use app\common\model\Type;
use app\common\validate\OfferDetailValidate;
use Exception;
use think\db\Query;
use think\Request;
use think\response\Json;

class OfferDetailController extends AdminBaseController {
	use AdminSettingForm;
	use SettingContent;
	/**
	 * 列表
	 * @param Request $request
	 * @param OfferDetail $model
	 * @return string
	 * @throws Exception
	 */
	public function index(Request $request, OfferDetail $model): string {
		$param = $request->param();
		$data = $model->with(['offer', 'school'])->scope('where', $param)
			->paginate([
				'list_rows' => $this->admin['admin_list_rows'],
				'var_page' => 'page',
				'query' => $request->get(),
			]);
		// 关键词，排序等赋值
		$this->assign($request->get());

		$this->assign([
			'data' => $data,
			'page' => $data->render(),
			'total' => $data->total(),
			'offer_list' => Offer::select(),
			'school_list' => School::select(),

		]);
		return $this->fetch();
	}

	/**
	 * 添加
	 * @param Request $request
	 * @param OfferDetail $model
	 * @param OfferDetailValidate $validate
	 * @return string|Json
	 * @throws Exception
	 */
	public function add(Request $request, OfferDetail $model, OfferDetailValidate $validate) {
		if ($request->isPost()) {
			$param = $request->param();
			try {
				$param['detail'] = $this->getOfferDetail($param);
			} catch (RuntimeException $exception) {
				return admin_error($exception->getMessage());
			}
			$validate_result = $validate->scene('admin_add')->check($param);
			if (!$validate_result) {
				return admin_error($validate->getError());
			}

			$result = $model::create($param);

			$url = URL_BACK;
			if (isset($param['_create']) && (int) $param['_create'] === 1) {
				$url = URL_RELOAD;
			}
			return $result ? admin_success('添加成功', [], $url) : admin_error();
		}
		$this->assign([
			'offer_list' => Offer::select(),
			'school_list' => School::select(),
			'type_list' => Type::where('parent_id', '<>', 0)->select(),
			'spec_list' => Spec::select(),
			'brand_list' => Brand::select(),
		]);

		return $this->fetch();
	}

	/**
	 * 修改
	 * @param $id
	 * @param Request $request
	 * @param OfferDetail $model
	 * @param OfferDetailValidate $validate
	 * @return string|Json
	 * @throws Exception
	 */
	public function edit($id, Request $request, OfferDetail $model, OfferDetailValidate $validate) {
		$data = $model->findOrEmpty($id);
		if ($request->isPost()) {
			$param = $request->param();
			try {
				$param['detail'] = $this->getOfferDetail($param);
			} catch (RuntimeException $exception) {
				return admin_error($exception->getMessage());
			}
			$check = $validate->scene('admin_edit')->check($param);
			if (!$check) {
				return admin_error($validate->getError());
			}
			$send = Send::where('id', $data['send_id'])->findOrEmpty();
			if (!$send->isEmpty()) {
				$send_detail = $send['detail'];
				foreach ($send['detail'] as $key => $Value) {

					$send_detail[$key]['type_id'] = $param['detail'][$key]['type_id'];
					$send_detail[$key]['spec_id'] = $param['detail'][$key]['spec_id'];
					$send_detail[$key]['brand_id'] = $param['detail'][$key]['brand_id'];
					$send_detail[$key]['num'] = $param['detail'][$key]['num'];
					$send_detail[$key]['money'] = round($send_detail[$key]['num'] * $send_detail[$key]['price'], 2);
				}
				$send_money = array_sum(array_column($send_detail, 'money'));
				$send->save(['detail' => $send_detail, 'money' => $send_money]);

				$offer_detail_list = OfferDetail::where('offer_id', $data['offer_id'])->select()->toArray();
				$filter_detail = array_column($offer_detail_list, 'detail');
				$twoDimArray = [];

				// 遍历三维数组，将其转换为二维数组
				foreach ($filter_detail as $subArray) {
					foreach ($subArray as $item) {
						$twoDimArray[] = $item;
					}
				}

				$filter_detail = $this->array_do($twoDimArray);

				$offer_data = [
					'money' => array_sum(array_column($offer_detail_list, 'money')),
					'detail' => $filter_detail,
				];
				$offer = Offer::where('id', $data['offer_id'])->update($offer_data);
			}
			$param['money'] = array_sum(array_column($param['detail'], 'money'));
			$result = $data->save($param);

			return $result ? admin_success('修改成功', [], URL_RELOAD) : admin_error('修改失败');
		}

		$this->assign([
			'data' => $data,
			'offer_list' => Offer::select(),
			'school_list' => School::select(),
			'type_list' => Type::where('parent_id', '<>', 0)->select(),
			'spec_list' => Spec::select(),
			'brand_list' => Brand::select(),
		]);

		return $this->fetch('add');
	}

	/**
	 * 删除
	 * @param mixed $id
	 * @param OfferDetail $model
	 * @return Json
	 */
	public function del($id, OfferDetail $model): Json {
		$check = $model->inNoDeletionIds($id);
		if (false !== $check) {
			return admin_error('ID为' . $check . '的数据不能被删除');
		}

		$result = $model::destroy(static function ($query) use ($id) {
			/** @var Query $query */
			$query->whereIn('id', $id);
		});

		return $result ? admin_success('删除成功', [], URL_RELOAD) : admin_error('删除失败');
	}

}
